package com.hnas.appLogin.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnas.appLogin.dao.VerifyCodeDao;
import com.hnas.appLogin.dto.DTOVerifyReturn;
import com.hnas.appLogin.orm.VerifyCode;
import com.hnas.appLogin.web.VerifyCodeControll;
import com.hnas.common.util.CommonUtils;
import com.hnas.common.util.ResultCode;
import com.hnas.core.app_common.util.CommonGetServerData;
import com.hnas.core.app_common.util.DTOResult;
import com.hnas.core.app_common.util.PostConnServer;
import com.hnas.core.app_common.util.Result;
import com.hnas.core.app_common.util.VerificationPostServer;
import com.hnas.core.dao.BaseDaoImpl;
import com.hnas.core.util.DateUtil;

@Component
public class VerifyCodeDaoImpl extends BaseDaoImpl<VerifyCode> implements VerifyCodeDao{
	
	@Value("#{component.SMS_BDT_VERIFYCODE}")
	private String SMS_BDT_VERIFYCODE;
	
	@Autowired
	private PostConnServer postConnServer;
	
    private static Log log = LogFactory.getLog(VerifyCodeControll.class);
	
	private static ObjectMapper objectMapper = new ObjectMapper();

	public VerifyCodeDaoImpl() {
		super(VerifyCode.class);
	}

	@Override
	public VerifyCode findNewBestCodeByPhoneNo(String phoneNo) {
		String now = DateUtil.dateTimeToString(new Date());
		List<VerifyCode> list = this.findByQuery("from VerifyCode t where t.phoneNo = ?1 and isDeleted=1 and str_to_date(t.expiryEndTime,'%Y-%m-%d %H:%i:%s')>str_to_date(?2,'%Y-%m-%d %H:%i:%s')  order by t.createTime desc", phoneNo,now);
		if(null!=list&&list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public void deleteByPhoneNo(String phoneNo) {
		String sql = "update tbl_verify_code set is_deleted=0 where phone_no='"+phoneNo+"'";
		Query query = this.getEntityManager().createNativeQuery(sql);
		query.executeUpdate();
	}

	@Override
	public String sendVerifyCode(String phoneNo, String type,String verificationTime) throws Exception{
		DTOResult dtoResult = new DTOResult();
		System.out.println("------------------------------获取短信验证码---开始------------------------------------");
		log.debug("------------------------------获取短信验证码---开始------------------------------------");
		String code = RandomCode();
		String verification = "["+code+","+verificationTime+"]";//获得验证码
		VerificationPostServer vps = new VerificationPostServer();//实例要发送到服务器的数据
		vps.setSmsNum(phoneNo);//短信号码
		vps.setTempId(SMS_BDT_VERIFYCODE);//宝岛通验证码模版
		vps.setSmsContent(verification);
		Map map = postConnServer.getRequestData(vps,"APP_SmsSend");//通过路由，获得数据APP_SmsSendNoPass APP_SmsSend
		JSON jsonData = (JSON) map.get("json");
		System.out.println("返回参数:"+jsonData.toJSONString());
		log.debug("返回参数:"+jsonData.toJSONString());
		CommonGetServerData cgsd = JSON.toJavaObject(jsonData, CommonGetServerData.class);//json转实体类
		Result rs = cgsd.getResult();
		String rsdStr = rs.getResultCode();
		if(rsdStr!=null&&rsdStr.equals("00000")){
			this.deleteByPhoneNo(phoneNo);
			VerifyCode ver = new VerifyCode();
			ver.setIsDeleted(true);
			ver.setVerifyCode(code);
			ver.setPhoneNo(phoneNo);
			ver.setVerifyType(Integer.parseInt(type));
			ver.setEffectTime(Long.parseLong(verificationTime));
			Long curr = new Date().getTime()+Long.parseLong(verificationTime)*60*1000;
			SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String expiryEndTime = sFormat.format(new Date(curr));
			ver.setExpiryEndTime(expiryEndTime);
			ver.setStatus(1);
			ver.setId(CommonUtils.getUUID());
			ver.setCreateTime(DateUtil.dateTimeToString(new Date()));
			ver.setUpdateTime(DateUtil.dateTimeToString(new Date()));
			this.persist(ver);
			DTOVerifyReturn dtoReturn = new DTOVerifyReturn();
			dtoReturn.setVerify_code(code);
			String resultData=objectMapper.writeValueAsString(dtoReturn);
			dtoResult.setResultCode(ResultCode.SUCCESS);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
			dtoResult.setResultData(resultData);
			return objectMapper.writeValueAsString(dtoResult);
		  }
		return null;
		
	}
	
	@SuppressWarnings("rawtypes")
	public String RandomCode() { 
		 String[] beforeShuffle = new String[] {"0" , "1" , "2" , "3", "4", "5", "6", "7",  "8", "9"};  
	     List list = Arrays.asList(beforeShuffle);  
	     Collections.shuffle(list);  
	     StringBuilder sb = new StringBuilder();  
	     for (int i = 0; i < list.size(); i++) {  
	         sb.append(list.get(i));  
	     }  
	     String afterShuffle = sb.toString();  
	     String result = afterShuffle.substring(5, 10);  
	    return result;
	}

}
